package com.dhy.parse;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Parameter;
import java.net.Socket;
import java.util.ArrayList;

import static com.dhy.constants.CommandTypeConstants.*;

/**
 * @author 大忽悠
 * @create 2022/5/29 20:21
 */
@Slf4j
public class StandardCommandParse implements CommandParse{
    private final Socket client;

    public StandardCommandParse(Socket client) {
        this.client = client;
    }


    @Override
    public Object parse() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        return doParse(reader);
    }

    public Object doParse(BufferedReader reader) throws IOException {
        //1.读取首字节--判断数据类型标识
        int first = reader.read();
        switch (first){
            //单行字符串,直接读取一行
            case ONE_LINE:
                return reader.readLine();
            //异常,读取一行
            case  ERROR:
                throw new RuntimeException(reader.readLine());
            //数字
            case NUMBER:
                return Long.parseLong(reader.readLine());
            //多行字符串
            case MULTIPLY_LINE:
                return parseMultiplyLine(Integer.valueOf(reader.readLine()),reader.readLine());
            //数组
            case ARRAY:
                return parseArray(reader);
            default:
                throw new RuntimeException("错误格式!");
        }
    }

    private Object parseArray(BufferedReader reader) throws IOException {
       //获取数组大小
        int len = Integer.parseInt(reader.readLine());
       if(len<=0) {
           return null;
       }
       //定义集合,接收多个元素
        ArrayList<Object> objects = new ArrayList<>(len);
       //遍历依次读取每个元素
        for (int i = 0; i < len; i++) {
            objects.add(doParse(reader));
        }
        return objects;
    }

    private Object parseMultiplyLine(Integer len, String str) {
         if(len==-1){
             return null;
         }
         if(len==0){
             return "";
         }
         //读len个字节,我们假设没有特殊字符,所以直接读取一行
         return str;
    }
}
